package model

import (
	"blog/global"
	"blog/model/response"
	"gorm.io/gorm"
)

type Category struct {
	ID   uint   `gorm:"primary_key;auto_increment" json:"id"`
	Name string `gorm:"type:varchar(20);not null" json:"name"`
}

//查询分类是否存在
func CheckCategory(name string) int {
	var category Category
	global.DB.Select("id").Where("name = ?", name).First(&category)
	if category.ID > 0 {
		return response.ERROR_CATENAME_USED

	}
	return response.SUCCESS
}

//添加分类
func CreateCategory(category *Category) int {
	err := global.DB.Create(&category).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS

}

//查询分类列表
func GetCategories(pageSize int, pageNum int) ([]Category, int64) {
	var categories []Category
	var total int64
	var err error
	if pageNum == 0 {
		err = global.DB.Limit(pageSize).Offset(-1).Find(&categories).Error
	} else {
		err = global.DB.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&categories).Error
	}
	global.DB.Model(&categories).Count(&total)
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return categories, total
}

//编辑分类
func EditCategory(id int, category *Category) int {
	var maps = make(map[string]interface{})
	maps["name"] = category.Name
	err := global.DB.Model(&Category{}).Where("id=?", id).Updates(maps).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS
}

//删除分类
func DeleteCategory(id int) int {
	var category Category
	err := global.DB.Where("id=?", id).Delete(&category).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS
}
